package cn.itcast.web.utils;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 日志切面类
 */
@Component
@Aspect
public class LogAspect {

   @Autowired
   private SysLogService logService;
   @Autowired
   private HttpServletRequest request;

   /**
    * 在执行控制器方法之后自动记录日志
    * @param pjp 可以获取当前执行的方法信息、目标对象
    * @return 控制器方法的返回值
    */
   @Around("bean(*Controller) && !bean(sysLogController)")
   public Object insertLog(ProceedingJoinPoint pjp){
      // 创建日志对象
      SysLog log = new SysLog();
      log.setIp(request.getRemoteAddr());
      log.setTime(new Date());

      // 设置当前执行的目标对象类全名（控制器类全名）
      log.setAction(pjp.getTarget().getClass().getName());
      // 设置当前执行的方法
      log.setMethod(pjp.getSignature().getName());

      User user = (User) request.getSession().getAttribute("loginUser");
      if (user != null) {
         log.setUserName(user.getUserName());
         log.setCompanyId(user.getCompanyId());
         log.setCompanyName(user.getCompanyName());
      }

      try {
         Object retV = pjp.proceed();
         // 记录日志
         logService.save(log);
         return retV;
      } catch (Throwable throwable) {
         throw new RuntimeException(throwable);
      }
   }
}